import { AfterViewInit, Component, ElementRef, OnInit, ViewChild } from '@angular/core';

declare const window: any, WebContainer: any;

@Component({
    selector: 'op-account-dashboard',
    templateUrl: './account-dashboard.component.html',
    styles: [
        `
        .my-class {
            width: 100px;
            background-color: aqua;
            /* word-break: keep-all; */
        }
        `
    ]
})
export class AccountDashboardComponent implements AfterViewInit, OnInit {
    @ViewChild('dynamicDiv', { static: false }) dynamicDiv: ElementRef;
    url: string = '[none]';
    fontSize: number = 13;

    timeList = [
        { topLabel: '第一次n', bottomLabel: '2019-11-01' },
        { topLabel: '第二次n', bottomLabel: '2019-11-02' },
        { topLabel: '第三次', bottomLabel: '2019-11-03' },
        { topLabel: '第四次', bottomLabel: '2019-11-04' },
        { topLabel: '第五次', bottomLabel: '2019-11-05' },
        { topLabel: '第六次', bottomLabel: '2019-11-06' },
        { topLabel: '第七次', bottomLabel: '2019-11-07' },
        { topLabel: '第八次', bottomLabel: '2019-11-08' },
        { topLabel: '第九次', bottomLabel: '2019-11-09' },
    ];

    constructor() {
        // Once we put the method on window object the keyword this will be undefined in the method body.
        // This line of the code makes sure bind it to current this context.
        this.pickImageCallback = this.pickImageCallback.bind(this);
    }

    ngOnInit(): void {
        // When interacting with native WebView we have to put the method on window object.
        // Otherwise native code will not be able to find this method.
        window.pickImageCallback = this.pickImageCallback;
    }

    ngAfterViewInit(): void {
        console.dir(this.dynamicDiv);
    }

    selectImage(): void {
        console.dir(this.dynamicDiv);

        // const divHeight = 22;

        // Why setInterval instead of while loop?
        // The while loop blokcs the rerender in call stack. That causes the infinit loop.
        // setInterval inserts a new task in the queue each time it runs.
        // One task completes with rerender.
        // let interval = setInterval(() => {
        //     if (this.dynamicDiv.nativeElement.clientHeight > divHeight) {
        //         this.fontSize--;
        //     } else {
        //         clearInterval(interval);
        //         interval = null;
        //     }
        // }, 1);

        // this.url = 'selectImage';

        // WebContainer.postMessage(JSON.stringify({
        //     methodName: 'pickImage',
        //     params: {
        //         id: 1,
        //         name: 'Name'
        //     },
        //     callback: {
        //         callbackName: 'pickImageCallback',
        //         paramNames: [
        //             'url'
        //         ]
        //     }
        // }));
    }

    private pickImageCallback(url: string): void {
        this.url = url;
    }
}